from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog
from core import *


def select_video():
    global stop_button
    stop_monitoring()
    file_path = filedialog.askopenfilename(filetypes=[("Video file", "*.mp4")])
    if file_path:
        stop_button['state'] = 'normal'
        start_detect_thread(file_path, detection_listener, 0, 120)


def stop_monitoring_event():
    global stop_button
    stop_button['state'] = 'disabled'
    stop_monitoring()


def detection_listener(image, result_num):
    global image_label
    global text_label

    image = Image.fromarray(image)
    image.thumbnail((500, 500))
    img_tk = ImageTk.PhotoImage(image)
    image_label.config(image=img_tk)
    image_label.image = img_tk
    text_label.config(text="Population: " + str(result_num))


def show_window(use_npu=False):
    global stop_button
    global image_label
    global text_label

    root = tk.Tk()
    root.geometry("800x600")
    root.title("Scenic Spot Population Detector Demonstration (for Video)")
    select_button = tk.Button(root, text="Select a Video", command=select_video)
    stop_button = tk.Button(root, text="Stop Monitoring", command=stop_monitoring_event)
    image_label = tk.Label(root)
    text_label = tk.Label(root)
    select_button.pack()
    stop_button.pack()
    stop_button['state'] = 'disabled'
    text_label.pack()
    image_label.pack()

    set_inference_type("npu" if use_npu else "rvv")
    initialize()

    start_server_thread()

    root.mainloop()

